<?php
/******************************************************************************
 *
 *    OpenZoowa - Web App to manage events
 *    Copyright (C) 2008 Jesus Ruiz-Ayucar
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as
 *    published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *****************************************************************************/
   define('ZOOWA', true);
   showHead();
   switch($_GET['step']) {
      case '2':
         $link = @mysql_connect($_POST['db_host'], $_POST['db_user'], $_POST['db_pass']);
         if ($link) {
            if (mysql_select_db($_POST['db_name'])) {
               // Volvamos el contenido al fichero de configuración
               if (createConfigFile()) {
                  // Seguimos con la configuración del sitio
                  createDataBase($_POST['db_pre']);
                  showStep2();
               } else {
                  showStep1('No hay permisos para escribir en el fichero /config.php. En Linux: escriba: <pre>chmod 666 config.php</pre>');
               }
            } else {
               showStep1('Nombre de base de datos erróneo');
            }
         } else {
            showStep1('No se ha podido conectar a la base de datos');
         }
         break;
      case '3':
         include_once('../config.php');
         $errors = null;
         if (empty($_POST['domain'])) {
            $errors = 'Debe especificar un nombre de dominio<br />';
         }

         if (empty($_POST['login'])) {
            $errors = 'Debe especificar un nombre de usuario administrador<br />';
         }

         if (empty($_POST['pass1']) || ($_POST['pass1'] != $_POST['pass2'])) {
            $errors = 'Las contraseñas deben coincidir y no estar vacías<br />';
         }

         if (empty($_POST['email'])) {
            $errors = 'Debe especificar un correo electrónico<br />';
         }

         if (!isset($errors)) {
            global $db;
            $db->query('DELETE FROM '.$GLOBALS['db_pre'].'config');
            $SQL = 'INSERT INTO '.$GLOBALS['db_pre'].'config VALUES("base_url","'.$db->escape($_POST['base_url']).'/")';
            $db->query($SQL);
            $SQL = 'INSERT INTO '.$GLOBALS['db_pre'].'config VALUES("site_name","'.$db->escape($_POST['name']).'")';
            $db->query($SQL);
            $SQL = 'INSERT INTO '.$GLOBALS['db_pre'].'config VALUES("domain","'.$db->escape($_POST['domain']).'")';
            $db->query($SQL);
            $SQL = 'INSERT INTO '.$GLOBALS['db_pre'].'config VALUES("cookiname","openzoowa")';
            $db->query($SQL);
            $SQL = 'INSERT INTO '.$GLOBALS['db_pre'].'config VALUES("language","es")';
            $db->query($SQL);
            $SQL = 'INSERT INTO '.$GLOBALS['db_pre'].'config VALUES("theme","default")';
            $db->query($SQL);
            $SQL = 'INSERT INTO '.$GLOBALS['db_pre'].'users(login, email, password, register_date, level) VALUES('.
               '"'.$db->escape($_POST['login']).'",'.
               '"'.$db->escape($_POST['email']).'",'.
               '"'.$db->escape(md5($_POST['pass1'])).'",'.
               'NOW(),'.
               '"admin")';
            $db->query($SQL);
            showStep3();
         } else {
            showStep2($errors);
         }
         break;
      default:
         showStep1();
   }
   showFoot();

   function createConfigFile() {
      $fp = @fopen("../config.php", "w");
      if ($fp) {
         fwrite($fp, "<?php\n   ".'$GLOBALS["db_server"]'."   = '127.0.0.1';\n   ".'$GLOBALS["db_name"]'."     = '".$_POST['db_name']."';\n   ".'$GLOBALS["db_user"]'."     = '".$_POST['db_user']."';\n   ".'$GLOBALS["db_password"]'." = '".$_POST['db_pass']."';\n   ".'$GLOBALS["db_pre"]'."      = '".$_POST['db_pre']."';\n\n   define('ZOOWA', true);\n   require_once('z-include/utilities/util.php');\n   Util::setConfig(dirname(__FILE__));\n?>");
         fclose($fp);
         return true;
      }
      return false;
   }

   function createDataBase($pre) {
      $fp = fopen('database.sql', 'r');
      if ($fp) {
         $content = fread($fp, filesize('database.sql'));
         $queries = explode(';',$content);
         foreach($queries as $SQL) {
            $patt[0] = '/DROP TABLE IF EXISTS `/i';
            $patt[1] = '/CREATE TABLE IF NOT EXISTS `/i';
            $patt[2] = '/INSERT INTO `/i';
            $repl[0] = 'DROP TABLE IF EXISTS `'.$pre;
            $repl[1] = 'CREATE TABLE IF NOT EXISTS `'.$pre;
            $repl[2] = 'INSERT INTO `'.$pre;
            $SQL = preg_replace($patt, $repl, $SQL);
            mysql_query($SQL);
         }
         return true;
      }
      return false;
   }

   function showStep3() {
?>
      <h1>Paso 3</h1>
      <h2>Finalización de la instalación</h2>
      <p>¡Felicidades! Ha instalado correctamente su agenda OpenZoowa.</p>
      <p>Para terminar la instalación, le pedimos que lleve a cabo las siguientes tareas:</p>
      <ol>
         <li>Elimine la carpeta /install</li>
         <li>Modifique los permisos del fichero /config.php. En Linux: <pre>chmod 655 config.php</pre></li>
      </ol>
      <a href="<?=$_POST['base_url']?>/">Ver su agenda OpenZoowa</a>
<?php
   }

   function showStep2($error = '') {
?>
      <h1>Paso 2</h1>
      <h2>Configuración del sitio</h2>
      <?php if (!empty($error)) { ?><strong>Error:</strong> <?=$error?><br /><?php } ?>
      <form action="?step=3" method="post">
         <h3>Parametros globales</h3>
         <table>
            <tr>
               <td>Nombre de dominio</td>
               <td>
                  <input type="text" name="domain" />
                  Por ejemplo, www.example.com
               </td>
            </tr>
            <tr>
               <td>Nombre de la página</td>
               <td>
                  <input type="text" name="name" />
                  Por ejemplo, "Página de la Asociación AFAT"
               </td>
            </tr>
            <tr>
               <td>Carpeta</td>
               <td>
                  <input type="text" name="base_url" />
                  Si la aplicación no va a estar en el directorio raiz. Por ejemplo "/agenda"
               </td>
            </tr>
         </table>
         <hr />
         <h3>Usuario administrador</h3>
         <table>
            <tr>
               <td>Login</td>
               <td><input type="text" name="login" /></td>
            </tr>
            <tr>
               <td>Contraseña</td>
               <td><input type="password" name="pass1" /><br /><input type="password" name="pass2" /></td>
            </tr>
            <tr>
               <td>Correo</td>
               <td><input type="text" name="email" /></td>
            </tr>
         </table>
         <button type="submit">Siguiente</button>
      </form>
<?php
   }

   function showStep1($error = '') {
?>
      <h1>Paso 1</h1>
      <h2>Configuración de la base de datos</h2>
      <?php if (!empty($error)) { ?><strong>Error:</strong> <?=$error?><br /><?php } ?>
      <form action="?step=2" method="post">
         <table>
            <tr>
               <td>host</td>
               <td><input type="text" name="db_host" value="<?=$_POST['db_host']?>"/></td>
            </tr>
            <tr>
               <td>user</td>
               <td><input type="text" name="db_user" value="<?=$_POST['db_user']?>" /></td>
            </tr>
            <tr>
               <td>password</td>
               <td><input type="password" name="db_pass" /></td>
            </tr>
            <tr>
               <td>base de datos</td>
               <td><input type="text" name="db_name" value="<?=$_POST['db_name']?>" /></td>
            </tr>
            <tr>
               <td>prefijo</td>
               <td><input type="text" name="db_pre" value="<?=$_POST['db_pre']?>" /></td>
            </tr>
            <tr>
               <td><button type="submit">Siguiente &raquo;</button></td>
            </tr>
         </table>
      </form>
<?php
   }

   function showHead() {
?>
<html>
   <head>
      <title>Instalador de OpenZoowa</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   </head>
   <body>
<?php
   }

   function showFoot() {
?>
   </body>
</html>
<?php
   }
?>